<template>
  <div class="bgc-default pad-20">
    <div class="bg-color-white pad-20">
      <div>
        <el-button type="primary" @click="buttonAdd">添加</el-button>
        <el-button type="primary" class="mar-l-20" plain @click="buttonCode">H5二维码</el-button>
      </div>
      <div class="top-operate-default mar-t-15">
        <div class="search-item">
          <label>搜索合伙人：</label>
          <el-select v-model="textCol" placeholder="请选择" style="width: 150px">
            <el-option label="合伙人名称" value="partnerName"></el-option>
            <el-option label="联系人" value="realName"></el-option>
            <el-option label="联系电话" value="phone"></el-option>
            <el-option label="店主昵称" value="memberNickname"></el-option>
            <el-option label="店主手机号" value="memberPhone"></el-option>
          </el-select>
          <el-input v-model="textValue" @keyup.enter.native="handleSearch" placeholder="请输入搜索内容" style="width: 150px">
          </el-input>
          <label class="mar-l-20">创建时间：</label>
          <el-date-picker v-model="datePicker" type="daterange" unlink-panels range-separator="至"
            value-format="yyyy-MM-dd" start-placeholder="创建开始时间" end-placeholder="创建结束时间"
            :picker-options="pickerOptions">
          </el-date-picker>
          <label class="mar-l-20">等级：</label>
          <el-select v-model="partnerGradeId" placeholder="请选择等级" class="pad-l-10 select-width">
           <el-option label="全部" value=""></el-option>
           <el-option v-for="item in partnerGradeIdList" :key="item.partnerGradeId" :label="item.gradeName"
              :value="item.partnerGradeId">
            </el-option>
          </el-select>
          <label class="mar-l-20">状态：</label>
          <el-select v-model="partnerStatus" placeholder="请选择状态" class="pad-l-10">
            <el-option v-for="item in partnerStatuss" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <el-button-group class="mar-l-20">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button plain="" @click="resetSearch">重置</el-button>
          </el-button-group>
        </div>
      </div>
      <!-- 全选、操作 -->
      <div>
        <div class="pad-t-15 pad-b-15 font-14 v-align-c">
          <el-checkbox class="mar-l-14 mar-r-0" v-model="allChecked" @change="selectAll"><span
              class="mar-l-20">当页全选</span></el-checkbox>
          <span class="pad-l-4 pad-r-4">|</span>
          <div class="width-80">已选{{multipleSelection.length}}项</div>
          <el-button class="batch-btn" @click="handleCommand('0')">批量启用</el-button>
          <el-button class="batch-btn" @click="handleCommand('1')">批量禁用</el-button>
        </div>
      </div>
      <!-- 内容列表 -->
      <div class="table-container">
        <el-table ref="multipleTable" :data="entityList" @selection-change="handleSelectionChange"
          v-loading="listLoading" element-loading-text="加载中" style="width: 100%" header-cell-class-name="default-header"
          row-class-name="default-row">
          <el-table-column width="50px" type="selection"></el-table-column>
          <el-table-column width="190px" label="合伙人名称" prop="partnerName" fixed="left">
            <template slot-scope="scope">
              <div>
                {{ scope.row.partnerName }}
              </div>
              <div>
                联系人：{{ scope.row.realName }}
              </div>
              <div>
                手机号: {{ scope.row.phone }}
              </div>
            </template>
          </el-table-column>
          <el-table-column width="200px" label="等级" prop="partnerGradeName"></el-table-column>
          <el-table-column width="250px" label="关联店主" prop="memberName">
            <template slot-scope="scope">
              <div v-if="scope.row.memberAvatar" style="float: left">
                <img :src="scope.row.memberAvatar" class="avatar-img mar-r-8">
              </div>
              <div v-if="scope.row.memberNickname" style="float: left; margin-left: 2px">
                <div>
                  昵称：{{ scope.row.memberNickname }}
                </div>
                <div>
                  手机：{{ scope.row.memberPhone }}
                </div>
              </div>
              <div v-else style="float: left; margin-left: 2px; color: #c3c4c5">—</div>
            </template>
          </el-table-column>
          <el-table-column width="200px" label="地址" prop="address"></el-table-column>
          <el-table-column width="160px" label="下级合伙人数" prop="twoPartnerNum"></el-table-column>
          <el-table-column width="160px" label="已激活云店数" prop="veekerNum">
            <template slot-scope="scope">
              <span>{{ scope.row.oneMemberNum + scope.row.twoMemberNum }}</span><br />
              <span><span class="font-color-9">直接发展:</span> {{ scope.row.oneMemberNum }}</span><br />
              <span><span class="font-color-9">下级发展:</span> {{ scope.row.twoMemberNum }}</span>
            </template>
          </el-table-column>
          <el-table-column width="160px" label="招募主播数">
            <template slot-scope="scope">
              <span>{{ scope.row.oneRecruitedAnchorNum + scope.row.twoRecruitedAnchorNum ? scope.row.oneRecruitedAnchorNum + scope.row.twoRecruitedAnchorNum : 0 }}</span><br />
              <span><span class="font-color-9">直接发展:</span>
                {{ scope.row.oneRecruitedAnchorNum ? scope.row.oneRecruitedAnchorNum : 0 }}</span><br />
              <span><span class="font-color-9">下级发展:</span>
                {{ scope.row.twoRecruitedAnchorNum ? scope.row.twoRecruitedAnchorNum : 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column width="200px" label="创建时间" prop="createTime"></el-table-column>
          <el-table-column width="160px" label="状态" prop="statusFlag">
            <template slot-scope="scope">
              <span v-if="scope.row.partnerStatus == 0">启用</span>
              <span v-else>禁用</span>
            </template>
          </el-table-column>
          <el-table-column min-width="220px" label="操作" align="right" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="medium" @click="updateEntity(scope.row)">编辑</el-button>
              <el-button type="text" size="medium" @click="updateStatus(scope.row.partnerId, 0)"
                v-if="scope.row.partnerStatus == 1">启用</el-button>
              <el-button type="text" size="medium" @click="updateStatus(scope.row.partnerId, 1)"
                v-if="scope.row.partnerStatus == 0">停用</el-button>
              <el-button type="text" size="medium" @click="handleDelete(scope.row.partnerId)"
                v-if="scope.row.partnerStatus == 1">删除</el-button>
              <el-button type="text" size="medium" @click="doResetPwd(scope.row.partnerId)">重置密码</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="searchListQuery.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="searchListQuery.size"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>

    <!-- 添加/编辑 -->
    <div>
      <el-dialog width="800px" v-el-drag-dialog :visible.sync="dialogFormVisible" :before-close="handleDialogClose">
        <el-form ref="recruiterForm" :model="form" :rules="rules" label-position="right" label-width="160px"
          style='width: 80%; margin-left:50px;'>
          <el-row>
            <el-form-item label-width="120px" label="合伙人名称" prop="partnerName">
              <el-input v-model="form.partnerName" placeholder="请输入合伙人名称"></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label-width="120px" label="联系人" prop="realName">
              <el-input v-model="form.realName" type="tel" placeholder="请输入联系人姓名"></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label-width="120px" label="手机号" prop="phone">
              <el-input v-model="form.phone" type="tel" placeholder="请输入手机号" maxlength="11"
                oninput="this.value=this.value.replace(/^[0,2,3,4,5,6,7,8,9]*$/gi,'')"
                onkeyup="this.value=this.value.replace(/\D/g,'')" :disabled="phoneBoolean"></el-input>
            </el-form-item>
            <el-form-item label-width="120px" label="等级" prop="partnerGradeId">
              <el-select v-model="form.partnerGradeId" placeholder="请选择等级" @change="handlePartnerGrade">
                <el-option v-for="item in partnerGradeIdList" :key="item.partnerGradeId" :label="item.gradeName"
                  :value="item.partnerGradeId">
                </el-option>
              </el-select>
              <span v-if="form.partnerGradeId">佣金比例：<span style="color: red;">{{ form.partnerGradeRate}}%</span></span>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label-width="120px" label="地址">
              <div class="flex">
                <el-select class="mar-r-3" v-model="provinceCode" size="small" filterable placeholder="请选择省份"
                  @change="changeProvince()">
                  <el-option v-for="item in provinceList" :key="item.areaCode" :label="item.areaName"
                    :value="item.areaCode">
                  </el-option>
                </el-select>
                <el-select class="mar-r-3" v-model="cityCode" size="small" filterable placeholder="请选择城市"
                  @change="changeCity()">
                  <el-option v-for="item in userCityList" :key="item.areaCode" :label="item.areaName"
                    :value="item.areaCode">
                  </el-option>
                </el-select>
                <el-select v-model="districtCode" filterable size="small" placeholder="请选择区县">
                  <el-option v-for="item in userDistrictList" :key="item.areaCode" :label="item.areaName"
                    :value="item.areaCode">
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label-width="120px" label="">
              <el-input v-model="form.address" placeholder="请输入详细地址"></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label-width="120px" label="提成比例" prop="royaltyRatio">
              <el-input v-model="form.royaltyRatio" placeholder="提成比例限制在0~100之间">
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="saveData">确定</el-button>
        </div>
      </el-dialog>
    </div>

    <!-- 添加内部微客弹窗 -->
    <el-dialog title="" :visible.sync="codeVisible" :close-on-press-escape="true" width="400px">
      <div class="text-align-c">
        <img :src="enterpriseH5QRCode" v-if="enterpriseH5QRCode" style="width: 200px">
      </div>
      <div class="text-align-c">
        <div>点击右键保存图片并发送给合伙人，</div>
        <div>通过它登录移动端管理页面</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="codeVisible = false">关闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
  import {
    getEnterprisePartnerGradeList
  } from '@/api/user/enterprisePartnerGrade'
  import {
    pagingPartner,
    updateBatchStatus,
    savePartner,
    doResetPwd,
    deleteById,
    getEnterpriseH5QRCode
  } from '@/api/user/enterprisePartner'
  import elDragDialog from '@/directive/el-dragDialog' // base on element-ui
  import Tinymce from '@/components/Tinymce'
  import {
    listArea
  } from '@/api/area/area'
  import {
    listCity,
    listDistrict
  } from '@/api/area/area'
  export default {
    components: {
      Tinymce
    },
    directives: {
      // 拖动窗口
      elDragDialog
    },
    data() {
      return {
        partnerStatuss: [{
          value: '',
          label: '全部'
        }, {
          value: '0',
          label: '启用'
        }, {
          value: '1',
          label: '禁用'
        }],
        // 搜索框下拉选项
        textCol: 'partnerName',
        // 搜索值
        textValue: '',
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        },
        phoneBoolean: true,
        partnerStatus: '',
        datePicker: [],
        entityList: [],
        total: null,
        listLoading: true,
        multipleSelection: [],
        // 默认条件
        defaultQuery: {
          enterpriseId: '',
          currentPage: 1,
          size: 10,
          partnerType: 1,
          startTime: '',
          endTime: '',
          partnerGradeId: ''
        },
        // 查询条件
        searchListQuery: {
          partnerGradeId: ''
        },
        partnerIds: [],
        form: {
          partnerName: '',
          realName: '',
          partnerGradeRate: '',
          address: '',
          royaltyRatio: '',
          partnerGradeId: ''
        },
        searchKeyword: '',
        provinceCode: '',
        cityCode: '',
        districtCode: '',
        provinceList: [],
        cityList: [],
        districtList: [],
        userCityList: [],
        userDistrictList: [],
        dialogFormVisible: false,
        dialogStatus: '',
        isHaveDict: false,
        codeVisible: false,
        enterpriseH5QRCode: '',
        recruiterCount: 0,
        memberCount: 0,
        partnerGradeId: '',
        rules: {
          partnerName: [{
            required: true,
            message: '请输入合伙人名称',
            trigger: 'blur'
          }],
          realName: [{
            required: true,
            message: '请输入姓名',
            trigger: 'blur'
          }],
          phone: [{
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          }],
          royaltyRatio: [{
            required: false,
            message: '请输入提成比例',
            trigger: 'blur'
          },
          {
            pattern: /(^(\d|[1-9]\d|100)(\.\d{1,2})?$)/,
            message: '请输入正确提成比例'
          }
          ],
          partnerGradeId: [{
            required: true,
            message: '请选择等级',
            trigger: 'change'
          }]
        },
        Map: {},
        allChecked: false,
        partnerGradeIdList: [],
        dateColumn: 'createTime'
      }
    },
    // 初始化页面
    created() {
      Object.assign(this.searchListQuery, this.defaultQuery)
      const queryParams = this.getCurrentPage().query
      if (queryParams.partnerGradeId) {
        this.partnerGradeId = queryParams.partnerGradeId
      }
      this.getEnterprisePartnerGradeList()
      this.initEntityList()
    },
    methods: {
      close() {
        this.dialogFormVisible = false
      },
      handleDialogClose() {
        this.dialogFormVisible = false
      },
      initEntityList() {
        this.setQueryCondition()
        this.listLoading = true
        pagingPartner(this.searchListQuery).then(response => {
          const entityList = response.data.records
          this.entityList = entityList
          this.total = response.data.total
          this.listLoading = false
        })
      },
      // 设置查询条件
      setQueryCondition() {
        const currentPage = this.searchListQuery.currentPage
        const size = this.searchListQuery.size
        this.searchListQuery = {
          ...this.defaultQuery
        }
        this.searchListQuery.size = size
        this.searchListQuery.currentPage = currentPage
        this.searchListQuery.enterpriseId = this.getEnterpriseId()
        this.searchListQuery[this.textCol] = this.textValue
        this.searchListQuery.partnerStatus = this.partnerStatus
        this.searchListQuery.partnerGradeId = this.partnerGradeId
        this.searchListQuery.dateColumn = this.dateColumn
        if (this.datePicker != null && this.datePicker.length > 0) {
          this.searchListQuery.startDate = this.datePicker[0] + ' 00:00:00'
          this.searchListQuery.endDate = this.datePicker[1] + ' 23:59:59'
        } else {
          this.searchListQuery.startDate = ''
          this.searchListQuery.endDate = ''
        }
      },
      handleCommand(command) {
        if (command === '0') {
          this.updateBatchStatus(0)
        }
        if (command === '1') {
          this.updateBatchStatus(1)
        }
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.initEntityList()
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initEntityList()
      },
      // 勾选
      handleSelectionChange(val) {
        this.multipleSelection = val
        if (this.multipleSelection.length === this.entityList.length) {
          this.allChecked = true
        } else {
          this.allChecked = false
        }
      },
      // 查询
      handleSearch() {
        this.searchListQuery.currentPage = 1
        this.initEntityList()
      },
      // 重置查询参数
      resetSearch() {
        const originData = this.$options.data()
        this.textCol = originData.textCol
        this.textValue = originData.textValue
        this.defaultQuery = originData.defaultQuery
        this.partnerStatus = originData.partnerStatus
        this.datePicker = originData.datePicker
        this.partnerGradeId = ''
        this.handleSearch()
      },
      updateBatchStatus(status) {
        this.partnerIds = []
        if (this.multipleSelection.length > 0) {
          this.multipleSelection.forEach((item) => {
            this.partnerIds.push(item.partnerId)
          })
          updateBatchStatus(this.partnerIds.join(','), status).then(response => {
            if (response.isError) return
            this.initEntityList()
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
          })
        } else {
          this.$message.error('请选择要操作的数据')
        }
      },
      updateStatus(id, status) {
        updateBatchStatus(id, status).then(response => {
          if (response.isError) return
          this.initEntityList()
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
        })
      },
      // 添加
      buttonAdd() {
        this.phoneBoolean = false
        this.resetrecruiter()
        this.provinceCode = ''
        this.districtCode = ''
        this.cityCode = ''
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$set(this.form, 'partnerGradeId', this.partnerGradeIdList[0].partnerGradeId)
        // this.form.partnerGradeId = this.partnerGradeIdList[0].partnerGradeId
        this.handlePartnerGrade(this.form.partnerGradeId)
        // this.$refs['recruiterForm'].clearValidate()
        // this.$nextTick(() => {
  
        // })
        this.initAreaList()
      },
      buttonCode() {
        getEnterpriseH5QRCode(this.getEnterpriseId()).then(response => {
          if (response.isError) return
          this.enterpriseH5QRCode = response.data
        })
        this.codeVisible = true
      },
      // 清空信息
      resetrecruiter() {
        const originData = this.$options.data()
        this.form = originData.form
      },
      changeProvince() {
        this.cityCode = ''
        this.districtCode = ''
        const provinceCode = this.provinceCode
        let provinceId = null
        this.provinceList.filter(province => {
          if (province.areaCode === provinceCode) {
            provinceId = province.areaId
            return true
          }
        })
        const newArr = []
        this.cityList.forEach(city => {
          const parentId = city.parentId
          if (parentId === provinceId) {
            newArr.push(city)
          }
        })
        this.userCityList = newArr
      },
      changeCity() {
        this.districtCode = ''
        const cityCode = this.cityCode
        let provinceId = null
        this.cityList.filter(province => {
          if (province.areaCode === cityCode) {
            provinceId = province.areaId
            return true
          }
        })
        const newArr = []
        this.districtList.forEach(city => {
          const parentId = city.parentId
          if (parentId === provinceId) {
            newArr.push(city)
          }
        })
        this.userDistrictList = newArr
      },
      // 保存
      saveData() {
        const that = this
        this.$refs['recruiterForm'].validate((valid) => {
          if (valid) {
            if (this.form.partnerName.length > 50) {
              this.$message.error('合伙人名称限制1~50个字符')
              return
            }
            if (this.form.realName.length > 10) {
              this.$message.error('联系人限制1~10个字符')
              return
            }
            if (this.form.address !== undefined && this.form.address.length > 50) {
              this.$message.error('详细地址限制1~50个字符')
              return
            }
            if (this.form.phone.length !== 11) {
              this.$message.error('请输入正确的手机号')
              return
            }
            this.form.provinceCode = this.provinceCode
            this.form.cityCode = this.cityCode
            this.form.districtCode = this.districtCode
            this.form.enterpriseId = this.getEnterpriseId()
            savePartner(this.form).then((response) => {
              if (response.isError) {
                return
              }
              that.initEntityList()
              that.dialogFormVisible = false
              that.$message({
                type: 'success',
                message: '保存成功!'
              })
            })
          }
        })
      },
      // 编辑
      updateEntity(row) {
        this.phoneBoolean = true
        Object.assign(this.form, row)
        // add by zhengjl bug-5957 编辑的时候，密码要清空，不然会判断密码不为空，校验不相同就用最新的密码，导致密码一致被修改
        this.form.password = ''
        this.provinceCode = this.form.provinceCode
        this.cityCode = this.form.cityCode
        this.districtCode = this.form.districtCode
        this.initAreaList()
        if (this.provinceCode !== '') {
          listCity(this.provinceCode).then(response => {
            this.userCityList = response.data
          })
        }
        if (this.cityCode !== '') {
          listDistrict(this.cityCode).then(response => {
            this.userDistrictList = response.data
          })
        }
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.handlePartnerGrade(this.form.partnerGradeId)
        this.$nextTick(() => {
          this.$refs['recruiterForm'].clearValidate()
        })
      },
      initAreaList() {
        listArea().then(response => {
          this.provinceList = response.data.provinceList
          this.cityList = response.data.cityList
          this.districtList = response.data.districtList
        })
      },
      doResetPwd(id) {
        this.$confirm('此操作将重置密码, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          doResetPwd(id).then((response) => {
            if (response.isError) return
            this.initEntityList()
            this.$message({
              type: 'success',
              message: '成功!'
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      },
      // 删除
      handleDelete(id) {
        this.$confirm('此操作将删除合伙人，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteById(id).then((response) => {
            if (response.isError) return
            this.initEntityList()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          })
        }).catch(() => {})
      },
      // 查询等级下拉列表
      getEnterprisePartnerGradeList() {
        getEnterprisePartnerGradeList({
          enterpriseId: this.getEnterpriseId(),
          partnerType: 1
        }).then((response) => {
          if (response.isError) return
          this.partnerGradeIdList = response.data
        })
      },
      // 重置密码
      handlePassword(id) {
        this.$confirm('此操作将重置该招募员信息，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          doResetPwd(id).then(() => {
            this.$message({
              type: 'success',
              message: '重置成功!'
            })
          })
        }).catch(() => {})
      },
      selectAll() {
        if (this.multipleSelection.length === 0 || this.multipleSelection.length < this.entityList.length) {
          this.entityList.forEach(item => {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          })
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      },
      handlePartnerGrade(partnerGradeId) {
        this.partnerGradeIdList.forEach((item) => {
          if (item.partnerGradeId === partnerGradeId) {
            this.form.partnerGradeRate = item.commissionRate || 0.00 + '%'
            return
          }
        })
      }
    },
    // 过滤器
    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'success',
          2: 'danger'
        }
        return statusMap[status]
      }
    }
  }
</script>

<style lang="less" scoped>
  .avatar-img {
    width: 40px;
    height: 40px;
    border-radius: 100px;
  }
  .select-width {
    /deep/ .el-input {
      width: 220px;
    }
  }
</style>
